package com.seckill.access;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.seckill.constants.LoginConstant;
import com.seckill.domain.MiaoshaUser;
import com.seckill.redis.AccessKey;
import com.seckill.redis.RedisService;
import com.seckill.result.CodeMsg;
import com.seckill.result.Result;
import com.seckill.service.MiaoshaUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * 拦截器 1.通过拦截获取用户登录信息 2.接口限流。使用自定义注解AccessLimit来对固定接口限流。 解析AccessLimit注解
 *
 * @author yjw
 * @date 2022/3/20 1:32
 */
@Component
@Slf4j
public class AccessInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    MiaoshaUserService userService;

    @Autowired
    RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("AccessInterceptor start!");
        if (handler instanceof HandlerMethod) {
            //请求中获取用户信息
            MiaoshaUser user = getUser(request, response);
            //拦截器设置用户信息（参数处理器设置，可以让每个接口拿到MiaoshaUser）
            UserContext.setUserHolder(user);
            //接口限流
            return requestLimit(request, response,  (HandlerMethod) handler, user);
        }
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
    }

    private boolean requestLimit(HttpServletRequest request, HttpServletResponse response,
                                 HandlerMethod handlerMethod, MiaoshaUser user) throws Exception {
        AccessLimit accessLimit = handlerMethod.getMethodAnnotation(AccessLimit.class);
        if (Objects.isNull(accessLimit)) {
            return true;
        }
        int maxCount = accessLimit.maxCount();
        int seconds = accessLimit.seconds();
        boolean needLogin = accessLimit.needLogin();
        String key = request.getRequestURI();
        //登陆判断
        if (needLogin && Objects.isNull(user)) {
            render(response, CodeMsg.SESSION_ERROR);
            return false;
        }
        if (Objects.nonNull(user)) {
            key += "_" + user.getId();
        }
        //限流判断，接口访问次数判断
        AccessKey accessKey = AccessKey.withExpire(seconds);
        Integer count = redisService.get(accessKey, key, Integer.class);
        if (Objects.isNull(count)) {
            redisService.set(accessKey, key, 1);
        } else if (count < maxCount) {
            redisService.incr(accessKey, key);
        } else {
            render(response, CodeMsg.ACCESS_LIMIT_REACHED);
            return false;
        }
        return true;
    }

    private void render(HttpServletResponse response, CodeMsg cm) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        String str = JSON.toJSONString(Result.error(cm));
        out.write(str.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }

    private MiaoshaUser getUser(HttpServletRequest request, HttpServletResponse response) {
        String paramToken = request.getParameter(LoginConstant.COOKIE_NAME);
        String cookieToken = getCookieValue(request, LoginConstant.COOKIE_NAME);
        if (StrUtil.isEmpty(cookieToken) && StrUtil.isEmpty(paramToken)) {
            return null;
        }
        String token = StrUtil.isNotEmpty(paramToken) ? paramToken : cookieToken;
        MiaoshaUser miaoshaUser = userService.getMiaoshaUserByToken(token);
        //重置用户过期时间
        userService.addLoginUserInfo(response, token, miaoshaUser);
        return miaoshaUser;
    }

    private String getCookieValue(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length <= 0) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookieName)) {
                return cookie.getValue();
            }
        }
        return null;
    }


}
